﻿package com.nb.cms.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.free.common.utils.web.Servlets;
import com.nb.category.model.Category;
import com.nb.cms.model.Site;
import com.nb.cms.service.SiteService;
import com.nb.common.utils.CmsUtils;
import com.nb.common.utils.SearchFilter;
import com.nb.system.NewPager;

/**
 * site
 * @author mefly
 *
 */
@Controller
@RequestMapping("/admin/site")
public class SiteController {

	@Autowired
	private SiteService service;
	@Autowired
	private Dao dao;
	
	/**
	 * 
	 */
	@RequestMapping()
	public String tree() {
		return "jsp/site/list-site";
	}
	
	/**
	 * 列表
	 */
	@RequestMapping("/ajax_list")
	@ResponseBody
	public Map<String, Object> list(HttpServletRequest request,
			@RequestParam(value="page",defaultValue="1") int page,
			@RequestParam(value="pagesize",defaultValue="10") int pagesize) {
		
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		NewPager pager = new NewPager();
		pager.setPageNumber(page);
		pager.setPageSize(pagesize);
		pager.setFilters(filters);
		return service.queryPage(pager);
	}

	/**
	 */
	@RequestMapping("/input")
	public String input(HttpServletRequest request,
			@RequestParam(value="id",defaultValue="0",required=false) int id) {	
		if (id>0){
			request.setAttribute("ob", service.fetch(id));
		}
		return "jsp/site/input-site";
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public String delete(int id) {
		List list = dao.query(Category.class, Cnd.where("siteid","=",id));
		if (list.size()==0){
			service.delete(id);
			CmsUtils.removeCache("defaultSite");
			return "ok";
		}
		return ("fail");	
	}

	@RequestMapping("/save")
	public String save(Site en) {	
		if (en.getId()==null){
			//如果新建的第一个站点，则为默认站点
			if(service.getAll().size()==0){
				en.setIsdefault("1");
			}
			service.insert(en);
		}else{
			service.updateIgnoreNull(en);
		}
		CmsUtils.removeCache("defaultSite");
		return "common/success";
	}
	
	@RequestMapping("/update")
	@ResponseBody
	public String update(int id) {	
		dao.update(Site.class, Chain.make("isdefault","0"), null);
		dao.update(Site.class, Chain.make("isdefault","1"), Cnd.where("id","=",id));
		CmsUtils.removeCache("defaultSite");
		return "ok";
	}
}
